﻿<%@ WebHandler Language="C#" Class="RbContainerShipPlanDelayReason" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

/**
 * Description: 转工排产超期原因维护
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * create Date:2022-08-10
 */

public class RbContainerShipPlanDelayReason : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "getDelayData":
                    getDelayData(context);
                    break;
                case "getData":
                    getData(context);
                    break;
                case "insertData":
                    insertData(context);//添加MES数据
                    break;
                case "updateData":
                    updateData(context);//更新
                    break;
                case "deleteData":
                    deleteData(context);//删除
                    break;
                case "insertNotMESData":
                    insertNotMESData(context);//添加其他数据
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    //查询已维护数据
    void getData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            string sql = @"
SELECT  rb.factoryname,'热表分厂' tofactory,
        rb.productname,rb.productdesc,
        rb.containername,rb.qty,rb.workflowstepname,
        rb.receivedate,
        rb.needfinishdate,
        NVL(rb.finishdate,t.completedate) finishdate,
        rb.delayreason,
        rb.notes,
        e.fullname createemployee,rb.createdate,
        e2.fullname modifyemployee,rb.modifydate,
        rb.id,rb.sourcetype
FROM rbcontainershipplandelayreason rb
LEFT JOIN r_shipboard_jijia@mesreport t ON t.containername = rb.containername AND t.workflowstepname = rb.workflowstepname
LEFT JOIN employee e ON e.employeeid = rb.createemployeeid
LEFT JOIN employee e2 ON e2.employeeid = rb.modifyemployeeid
WHERE rb.isuse = 0 ";
            //主制分厂
            if (context.Request["factoryname"] != null && context.Request["factoryname"].ToString() != "")
            {
                sql += string.Format(" AND rb.factoryname = '{0}'", context.Request["factoryname"].ToString());
            }
            //批次号
            if (context.Request["containername"] != null && context.Request["containername"].ToString() != "")
            {
                sql += string.Format(" AND rb.containername LIKE '%{0}%'", context.Request["containername"].ToString());
            }
            //件号
            if (context.Request["productname"] != null && context.Request["productname"].ToString() != "")
            {
                sql += string.Format(" AND rb.productname LIKE '%{0}%'", context.Request["productname"].ToString());
            }
            //热表接收时间
            if (context.Request["recivedateStart"] != null && context.Request["recivedateStart"].ToString() != "")
            {
                sql += string.Format(" AND rb.receivedate >= to_date('{0}','yyyy-mm-dd')", context.Request["recivedateStart"].ToString());
            }
            if (context.Request["recivedateEnd"] != null && context.Request["recivedateEnd"].ToString() != "")
            {
                sql += string.Format(" AND rb.receivedate <= to_date('{0}','yyyy-mm-dd')", context.Request["recivedateEnd"].ToString());
            }
            //完成状态
            if (context.Request["status"] != null && context.Request["status"].ToString() != "全部")
            {
                string status = context.Request["status"].ToString();
                if (status == "已完成")
                {
                    sql += " AND rb.finishdate IS NOT NULL ";
                }
                else
                {
                    sql += " AND rb.finishdate IS NULL ";
                }
            }
            //数据来源
            if (context.Request["sourcetype"] != null && context.Request["sourcetype"].ToString() != "全部")
            {
                string sourcetype = context.Request["sourcetype"].ToString();
                if (sourcetype == "1")
                {
                    sql += " AND rb.sourcetype = 1";
                }
                else
                {
                    sql += " AND rb.sourcetype = 2";
                }
            }
            uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
            paraPage.CurrentPageIndex = Convert.ToInt32(context.Request.Form["pageNumber"].ToString());//页码
            paraPage.PageSize = Convert.ToInt32(context.Request.Form["PageSize"].ToString());//每页页数
            paraPage.strSQL = sql;
            uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
            foreach (DataColumn col in result.DBTable.Columns)
            {
                col.ColumnName = col.ColumnName.ToLower();
            }
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    // 查询已超期转工排产数据
    void getDelayData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            string sql = @"
SELECT t.factoryname fromfactoryname,t.tofactoryname,t.productname,t.productdescription,t.containername,cci.qty,t.workflowstepname,
       t.senddate,t.needcompletedate,t.estimatedcompletedate,t.recivedate receivedate,t.completedate,t.shipindate,t.plannedfinishdate,
       CASE WHEN t.shipindate IS NOT NULL THEN TRUNC(t.shipindate) - TRUNC(t.plannedfinishdate)
            WHEN t.shipindate IS  NULL THEN TRUNC(SYSDATE) - TRUNC(t.plannedfinishdate) 
       END delaydays
FROM r_shipboard_jijia@mesreport t
LEFT JOIN rbcontainershipplandelayreason c ON t.containername = c.containername AND t.workflowstepname = c.workflowstepname
LEFT JOIN containercurrentinfo cci ON cci.containername = t.containername
WHERE c.id IS NULL AND ((t.shipindate IS NOT NULL AND TRUNC(t.shipindate) > TRUNC(t.plannedfinishdate)) OR (t.shipindate IS NULL AND TRUNC(SYSDATE) > TRUNC(t.plannedfinishdate)))
";
            sql += string.Format(" AND t.tofactoryname = '{0}'", m_UserInfo.Factory);
            //主制分厂
            if (context.Request["factoryname"] != null && context.Request["factoryname"].ToString() != "")
            {
                sql += string.Format(" AND t.factoryname = '{0}'", context.Request["factoryname"].ToString());
            }
            //批次号
            if (context.Request["containername"] != null && context.Request["containername"].ToString() != "")
            {
                sql += string.Format(" AND t.containername LIKE '%{0}%'", context.Request["containername"].ToString());
            }
            //件号
            if (context.Request["productname"] != null && context.Request["productname"].ToString() != "")
            {
                sql += string.Format(" AND t.productname LIKE '%{0}%'", context.Request["productname"].ToString());
            }
            //热表接收时间
            if (context.Request["recivedateStart"] != null && context.Request["recivedateStart"].ToString() != "")
            {
                sql += string.Format(" AND TRUNC(t.recivedate) >= to_date('{0}','yyyy-mm-dd')", context.Request["recivedateStart"].ToString());
            }
            if (context.Request["recivedateEnd"] != null && context.Request["recivedateEnd"].ToString() != "")
            {
                sql += string.Format(" AND TRUNC(t.recivedate) <= to_date('{0}','yyyy-mm-dd')", context.Request["recivedateEnd"].ToString());
            }
            uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
            paraPage.CurrentPageIndex = Convert.ToInt32(context.Request.Form["pageNumber"].ToString());//页码
            paraPage.PageSize = Convert.ToInt32(context.Request.Form["PageSize"].ToString());//每页页数
            paraPage.strSQL = sql;
            uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
            foreach (DataColumn col in result.DBTable.Columns)
            {
                col.ColumnName = col.ColumnName.ToLower();
            }
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    //添加MES数据
    void insertData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            DataTable dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["selectData"].ToString());
            string delayReason = context.Request.Form["delayReason"].ToString();
            string notes = context.Request.Form["notes"].ToString();
            string createemployeeid = m_UserInfo.EmployeeID.ToString();
            string sql = "";
            foreach (DataRow dr in dtPostData.Rows)
            {
                sql = @"
INSERT INTO rbcontainershipplandelayreason(delayreason,notes,containername,workflowstepname,qty,factoryname,receivedate,needfinishdate,finishdate,productname,
                                           productdesc,sourcetype,id,createdate,createemployeeid)
VALUES('{0}','{1}','{2}','{3}','{4}','{5}',to_date('{6}','yyyy/mm/dd'),to_date('{7}','yyyy/mm/dd'),to_date('{8}','yyyy/mm/dd'),'{9}','{10}',1,'{11}',sysdate,'{12}')";

                sql = string.Format(sql, delayReason, //超期原因
                                         notes,//备注
                                         dr["containername"].ToString(),//批次号
                                         dr["workflowstepname"].ToString(),//工序
                                         dr["qty"].ToString(),//批次数量
                                         dr["fromfactoryname"].ToString(),//主制分厂
                                         dr["receivedate"].ToString() != "" ? dr["receivedate"].ToString().Split(' ')[0] : "",//接收时间
                                         dr["plannedfinishdate"].ToString() != "" ? dr["plannedfinishdate"].ToString().Split(' ')[0] : "",//要求完成时间
                                         dr["shipindate"].ToString() != "" ? dr["shipindate"].ToString().Split(' ')[0] : "",//完成时间
                                         dr["productname"].ToString(),//件号
                                         dr["productdescription"].ToString(),//件号名称
                                         Guid.NewGuid().ToString(), //唯一id
                                         createemployeeid);//创建人
                int insertResult = DatabaseHelper.ExecuteSql(sql);
            }
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
        }
    }

    //添加数据来源非MES数据
    void insertNotMESData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            DataTable dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["postData"].ToString());
            string createemployeeid = m_UserInfo.EmployeeID.ToString();
            string sql = "";
            foreach (DataRow dr in dtPostData.Rows)
            {
                sql = @"
INSERT INTO rbcontainershipplandelayreason(delayreason,notes,containername,workflowstepname,qty,factoryname,receivedate,needfinishdate,finishdate,productname,
                                           productdesc,sourcetype,id,createdate,createemployeeid)
VALUES('{0}','{1}','{2}','{3}','{4}','{5}',to_date('{6}','yyyy/mm/dd'),to_date('{7}','yyyy/mm/dd'),to_date('{8}','yyyy/mm/dd'),'{9}','{10}',2,'{11}',sysdate,'{12}')";

                sql = string.Format(sql, dr["delayreason"].ToString(), //超期原因
                                         dr["notes"].ToString(),//备注
                                         dr["containername"].ToString(),//批次号
                                         dr["workflowstepname"].ToString(),//工序
                                         dr["qty"].ToString(),//批次数量
                                         dr["fromfactoryname"].ToString(),//主制分厂
                                         dr["receivedate"].ToString() != "" ? dr["receivedate"].ToString().Split(' ')[0] : "",//接收时间
                                         dr["needfinishdate"].ToString() != "" ? dr["needfinishdate"].ToString().Split(' ')[0] : "",//要求完成时间
                                         dr["finishdate"].ToString() != "" ? dr["finishdate"].ToString().Split(' ')[0] : "",//完成时间
                                         dr["productname"].ToString(),//件号
                                         dr["productdescription"].ToString(),//件号名称
                                         Guid.NewGuid().ToString(), //唯一id
                                         createemployeeid);//创建人
                int insertResult = DatabaseHelper.ExecuteSql(sql);
            }
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
        }
    }

    //更新
    void updateData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            DataTable dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["selectData"].ToString());
            string delayreason = context.Request.Form["delayreason"].ToString();//超期原因
            string notes = context.Request.Form["notes"].ToString();//备注
            string modifyemployeeid = m_UserInfo.EmployeeID.ToString();//修改时间
            string finishdate = context.Request.Form["finishdate"].ToString();//完成时间
            if (finishdate != "")
            {
                finishdate = finishdate.Split(' ')[0];
            }
            string needfinishdate = context.Request.Form["needfinishdate"].ToString();//要求完成时间
            if (needfinishdate != "")
            {
                needfinishdate = needfinishdate.Split(' ')[0];
            }
            string sql = "";
            foreach (DataRow dr in dtPostData.Rows)
            {
                if (dr["finishdate"].ToString() != "")
                {
                    continue;
                }
                //非MES数据
                if (dr["sourcetype"].ToString() == "2" && finishdate != "")
                {
                    sql = @"
UPDATE rbcontainershipplandelayreason t SET t.modifyemployeeid = '{0}',
                                            t.modifydate = sysdate,
                                            t.delayreason = '{1}',
                                            t.notes = '{2}',
                                            t.finishdate = to_date('{3}','yyyy/mm/dd'),
                                            t.needfinishdate = to_date('{4}','yyyy/mm/dd')
WHERE t.id = '{5}'";
                    if (needfinishdate == "")
                    {
                        needfinishdate = dr["needfinishdate"].ToString().Split(' ')[0];
                    }
                    if (dr["finishdate"].ToString() != "")
                    {
                        finishdate = dr["finishdate"].ToString().Split(' ')[0];
                    }
                    sql = string.Format(sql, modifyemployeeid, delayreason, notes, finishdate, needfinishdate, dr["id"].ToString());
                    int insertResult = DatabaseHelper.ExecuteSql(sql);
                }
                else
                {
                    sql = @"
update rbcontainershipplandelayreason t SET t.modifyemployeeid = '{0}',
                                      t.modifydate = sysdate,
                                      t.delayreason = '{1}',
                                      t.notes = '{2}',
                                      t.needfinishdate = to_date('{3}','yyyy/mm/dd')
WHERE t.id = '{4}'";
                    if (needfinishdate == "")
                    {
                        needfinishdate = dr["needfinishdate"].ToString().Split(' ')[0];
                    }
                    sql = string.Format(sql, modifyemployeeid, delayreason, notes, needfinishdate, dr["id"].ToString());
                    int insertResult = DatabaseHelper.ExecuteSql(sql);
                }
            }
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
        }
    }

    //删除
    void deleteData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            DataTable dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["willBeDeleteData"].ToString());
            string sql = "";
            foreach (DataRow dr in dtPostData.Rows)
            {
                sql = string.Format("DELETE rbcontainershipplandelayreason t WHERE t.id = '{0}'", dr["id"].ToString());
                int insertResult = DatabaseHelper.ExecuteSql(sql);
            }
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
        }
    }
}